package day31;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: 王丹
 * @create: 2021-08-03 17:21
 * 方式2：CountDownLatch实现 Thread的join()方法实现:等待线程完成的方式
 **/
public class Demo02 {
    //用于封装结果
    static class Result<T> {
        T result;

        public T getResult() {
            return result;
        }

        public void setResult(T result) {
            this.result = result;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        System.out.println(System.currentTimeMillis());
        //用于存放子线程结果
        Demo01.Result<Integer> result = new Demo01.Result<>();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                    result.setResult(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            }
        });
        thread.start();
        //countDownLatch.await()会让当前线程阻塞，当countDownLatch中的计数器变为0的时
        //候，await方法会返回
        countDownLatch.await();
        Integer rs = result.getResult();
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() + ":" + rs);
    }
}
